﻿#include "widget.h"
#include "ui_widget.h"

#include <QSettings>
#include <QtConcurrent>
#include <QFileDialog>
#include <QDebug>
#include <chrono>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle(QStringLiteral("字符编码转换工具"));

    connect(this,&Widget::foundFile,this,[this](){
        ui->status->setText(QStringLiteral("找到文件 %1个").arg(fileIndex));
    },Qt::QueuedConnection);

    connect(this,&Widget::convertFile,this,[this](QString file){
        ui->textBrowser->append(file);
        ui->status->setText(QStringLiteral("转换文件 %1/%2个").arg(fileIndex).arg(fileCount));
    },Qt::QueuedConnection);
}

Widget::~Widget()
{
    delete ui;

    isStop=true;
}


void Widget::on_addBtn_clicked()
{
    QSettings settings("convert", "app");
    QString lastPath = settings.value("lastPath").toString();

    QString folderPath = QFileDialog::getExistingDirectory(nullptr, QStringLiteral("选择文件夹"), lastPath);
    if (!folderPath.isEmpty()) {
        settings.setValue("lastPath", folderPath);
        ui->sourceList->addItem(folderPath);
    } else {
        qDebug() << QStringLiteral("未选择文件夹");
    }
}

void Widget::on_delBtn_clicked()
{
    QListWidgetItem *itemToRemove = ui->sourceList->takeItem(ui->sourceList->currentRow());
    delete itemToRemove;
}


void Widget::on_startBtn_clicked()
{
    ui->textBrowser->clear();
    fileIndex=0;
    fileCount=0;
    isStop=false;
    fileVector.clear();
    ui->status->clear();

    QtConcurrent::run([&](){
        for(int i=0;i<ui->sourceList->count();i++){
            if(isStop)
                return;

            QString path = ui->sourceList->item(i)->text();

            QStringList suffixList = ui->suffixList->text().split(";");
            listFilesRecursively(path,suffixList);
        }

        if(fileVector.size()==0){
            ui->status->setText(QStringLiteral("未发现合适的文件，请检查后缀类型是否正确"));
        }

        fileCount.store(fileIndex.load());
        fileIndex=0;
        for(int j=0;j<fileVector.count();j++){
            if(isStop)
                return;

            QString file = fileVector.at(j);

            //开始转换
            changeFileCode(file,ui->addBom->isChecked());

            fileIndex+=1;
            emit convertFile(file);

            std::this_thread::sleep_for(std::chrono::nanoseconds(1000));
        }
    });
}


void Widget::on_stopBtn_clicked()
{
    isStop=true;
}

void Widget::changeFileCode(const QString &filePath, bool isAddBom ){
    if(!QFile::exists(filePath)) {
        qDebug() << QStringLiteral("文件不存在") << filePath;
        return;
    }

    QFile inputFile(filePath);
    if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << QStringLiteral("无法打开文件：") << filePath;
        return;
    }

    QTextStream inputStream(&inputFile);
    inputStream.setCodec("UTF-8");
    QString content = inputStream.readAll();
    inputFile.close();


    //（覆盖原始文件）
    QFile outputFile(filePath);
    if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        qDebug() << "无法创建文件：" << filePath;
        return;
    }

    QTextStream outputStream(&outputFile);
    outputStream.setCodec("UTF-8");
    outputStream.setGenerateByteOrderMark(isAddBom);
    outputStream << content;
    outputFile.close();
}

void Widget::listFilesRecursively(const QString &path, QStringList extension)
{
    QDir directory(path);
    if (!directory.exists()) {
        qDebug() << QStringLiteral("指定路径不存在");
        return;
    }

    directory.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    QFileInfoList fileList = directory.entryInfoList();
    foreach (const QFileInfo &fileInfo, fileList) {
        if (fileInfo.isDir()) {
            if(!ui->isTraverse->isChecked()){
                continue;
            }
            listFilesRecursively(fileInfo.filePath(), extension);
        } else {
            QString fileExtension = fileInfo.suffix().toLower();
            if (!fileExtension.isEmpty()&&!extension.filter(fileExtension,Qt::CaseInsensitive).isEmpty()) {
                fileVector.append(fileInfo.filePath());
                fileIndex+=1;

                emit foundFile();
            }
        }
    }
}

